<?php

namespace App\Service;

use App\Jobs\LoginSteampoweredRobotJob;
use App\lib\Api;
use App\Lib\CommonConf;
use App\Lib\Curl;
use App\Model\BotsModel;
use App\Model\UserWalletcodeModel;

class WalletcodeService extends BaseService
{
    public static $instance = null;

    public $pickNum = 0;

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    const VALIDATEWALLETCODE  = 'https://store.steampowered.com/account/validatewalletcode/';

    const CONFIRMREDEEMWALLETCODE  = 'https://store.steampowered.com/account/confirmredeemwalletcode/';

    /**
     * 创建充值数据
     * @param $walletcode
     * @param $steamId
     * @param $botId
     * @return array
     */
    public function createUserWalletcode($walletcode, $steamId, $botId)
    {
        $walletcode = strtoupper(trim($walletcode));
        $res = preg_match('#^[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}$#', $walletcode);

        if ($res <= 0) {
            return [Api::CODE_WALLET_CODE_NOT, []];
        }

        if($botId > 0){
            $botInfo = BotsModel::getBotsInfoBybotId($botId);
        }else{
            $botInfo = BotsModel::getWalletcodeBotsInfo();
        }
        $clientNo = $botInfo['client_no'];
        $botId = $botInfo['bot_id'];

//        list($code) = $this->rpcCheckWalletcode($walletcode, $clientNo, $botId);
//        if ($code != Api::CODE_OK) {
//            return [$code, []];
//        }

        $data['walletcode_no'] = self::createWalletcodeNo();
        $data['walletcode'] = $walletcode;
        $data['client_no'] = $clientNo;
        $data['bot_id'] = $botId;
        $data['steam_id'] = $steamId;

        $userWalletcodeId = UserWalletcodeModel::createUserWalletcode($data);

        if ($userWalletcodeId === false) {
            return [Api::CODE_WALLET_CODE_BAD, []];
        }

        $result = [
            'user_walletcode_id' => $userWalletcodeId,
            'walletcode_no' => $data['walletcode_no'],
            'message' => '充值中',
        ];
        return [Api::CODE_OK, $result];
    }

    /**
     * 生成充值流水号
     * @return string
     */
    public static function createWalletcodeNo()
    {
        return 'wcn' . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 检测steam钱包充值码
     * @param $walletcode
     * @param $botId
     * @return array
     */
    public function checkWalletcode($walletcode, $botId){
        if ($botId) {
            $bot = BotsModel::getWalletcodeBotsInfoBybotId($botId);
        }else{
            $bot = BotsModel::getWalletcodeBotsInfo();
        }
        if (empty($bot)) {
            return [Api::CODE_STEAM_TRADE_URL_SERVICE_BUSY, []];
        }

        $steampowered = $bot['steampowered'];
        if (empty($steampowered)  && $this->pickNum < 3) {
            $this->pickNum ++;
            $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
            dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
            return $this->checkWalletcode($walletcode, $botId);
        }

        if (empty($steampowered)){
            return [Api::CODE_FROM_TRADE_BOT_RETRY, []];
        }

        $response = $steampowered->cURL(self::VALIDATEWALLETCODE . '?wallet_code=' . $walletcode);
        $response = json_decode($response, true);

        if($response){
            if ($response['success'] == 1){
                return ($response['detail'] == 0) ? [Api::CODE_OK, []] : ($response['detail'] == 15)? [Api::CODE_WALLET_CODE_REPEAT, []] : [Api::CODE_WALLET_CODE_NOT, []];
            }else{
                return [Api::CODE_WALLET_CODE_NOT, []];
            }
        }else{
            return [Api::CODE_FROM_TRADE_BOT_RETRY, []];
        }
    }

    /**
     * rpc检测steam钱包充值码
     * @param $walletcode
     * @param string $clientNo
     * @param int $botId
     * @return array
     */
    public function rpcCheckWalletcode($walletcode, $clientNo, $botId)
    {
        $urlArr = CommonConf::$nodeUrlArr;

        $url = $urlArr[strtolower($clientNo)] . '/LAN/checkWalletcode';

        $param = array(
            'walletcode' => $walletcode,
            'botId' => $botId,
        );

        $res = Curl::http_post($url, SignService::getInstance()->initParamPost($param));
        $res = json_decode($res, true);

        if ($res['code'] == Api::CODE_OK) {
            return [Api::CODE_OK, $res['result']];
        } else {
            return [$res['code'], []];
        }
    }

    /**
     * 获取steam钱包充值记录详细信息
     * @param $userWalletcodeId
     * @return array
     */
    public function getUserWalletcodeInfo($userWalletcodeId)
    {
        $userWalletcodeInfo = UserWalletcodeModel::getUserWalletcodeByUserWalletcodeId($userWalletcodeId);
        if (empty($userWalletcodeInfo)) {
            return [Api::CODE_NOT_WALLET_CODE, []];
        }

        $arr['user_walletcode_id'] = $userWalletcodeInfo['user_walletcode_id'];
        $arr['walletcode_no'] = $userWalletcodeInfo['walletcode_no'];
        $arr['bot_balance_front'] = $userWalletcodeInfo['bot_balance_front'];
        $arr['money'] = $userWalletcodeInfo['money'];
        $arr['bot_balance_after'] = $userWalletcodeInfo['bot_balance_after'];
        $arr['walletcode_status'] = $userWalletcodeInfo['walletcode_status'];
        $arr['detail'] = $userWalletcodeInfo['detail'];

        return [Api::CODE_OK, $arr];
    }

    /**
     * 获取机器人钱包
     * @return array
     */
    public function getBotBalance()
    {
        $bot = BotsModel::getWalletcodeBotsInfo();
        $steampowered = $bot['steampowered'];

        $botBalance = $steampowered->market()->getWalletBalanceCustom();
        if ($botBalance === 'nologin') {
            $currentQueue = 'LoginSteampoweredRobotJob_' . $bot['client_no'];
            dispatch((new LoginSteampoweredRobotJob($bot['bot_id']))->onQueue($currentQueue)->delay(1));
            return [Api::CODE_OK, ['bot_balance' => false]];
        }

        if ($botBalance === false) {
            return [Api::CODE_OK, ['bot_balance' => false]];
        }

        return [Api::CODE_OK, ['bot_balance' => $botBalance]];
    }
}